package org.zoomdev.android.nfccard.cpu;


import org.zoomdev.android.nfc.adapters.ApduException;
import org.zoomdev.android.nfc.adapters.IsoDepTagAdapter;
import org.zoomdev.android.nfccard.NfcResult;

import java.io.IOException;

public class CpuCardModel {

    private IsoDepTagAdapter adapter;
    private CardReader cardReader;
    private CpuCard cpuCard = new CpuCard();

    public CpuCardModel(IsoDepTagAdapter adapter) throws IOException, ApduException {
        this.adapter = adapter;
        this.cardReader = createReader();
    }

    protected void selectFile(IsoDepTagAdapter adapter, boolean byName, String file) throws IOException, ApduException {
        if (file.length() % 2 > 0) {
            throw new RuntimeException("文件标识或者名称长度必须为偶数");
        }

        Utils.send(adapter,String.format("00a4%s00%02x%s", byName ? "04" : "00", file.length() / 2, file));
    }


    public CardReader createReader() throws IOException, ApduException {
        if (adapter == null) {
            throw new IOException();
        }
        try {

            if (!adapter.isConnected()) {
                adapter.connect();
            }
            //交通不卡
            selectFile(adapter, true, "A000000632010105");
            return new TransCardReader();
        } catch (ApduException e) {
            //cpu卡
            selectFile(adapter, false, "3f00");
            return new CpuCardReader();
        }
    }

    /**
     * 获取卡片信息
     *
     * @return
     * @throws IOException
     * @throws ApduException
     */
    public NfcResult getCardInfo() throws IOException, ApduException {
        return cardReader.getAll(cpuCard, adapter);
    }

    public String getCardId() throws IOException, ApduException {
        if (cardReader == null || adapter == null) {
            throw new IOException();
        }
        return cardReader.getCardId(cpuCard, adapter);
    }


    /**
     * @return
     * @throws IOException
     * @throws ApduException
     */
    public CardReader.ChargeInfo getOtherRechargeInfo() throws IOException, ApduException {
        if (cardReader == null || adapter == null) {
            throw new IOException();
        }
        //0015
        return cardReader.getOtherRechargeInfo(cpuCard, adapter);
    }


}
